<template>
  <div id="role">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable
                @close="removeRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2===0?'':'bdtop','vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable
                    @close="removeRightById(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable
                      @close="removeRightById(scope.row,item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除
            </el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-form :model="addForm" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRole">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="70px" ref="editFormRef">
        <el-form-item label="角色名">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="mobile">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editRole()">确 定</el-button>
        <el-button @click="editDialogClosed">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 设置权限 -->
    <el-dialog title="设置权限" :visible.sync="setRightDialogVisible">
        <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary"  @click="allotRights">确 定</el-button>
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'role',
    data() {
      return {
        //所有角色列表数据
        roleList: [],
        addDialogVisible: false,
        addForm: {
          roleName: '',
          roleDesc: ''
        },
        editDialogVisible: false,
        editForm: {},
        setRightDialogVisible:false,
        rightsList:[],
        // 树形控件的属性绑定对象
        treeProps:{
            label:'authName',
            children:'children'
        },
        // 默认选中的节点id值
        defkeys:[],
        // 当前即将分配权限的角色id
        roleId:''
      }
    },
    created() {
      this.getRoleList()
    },
    methods: {
      // 获取所有角色列表数据
      async getRoleList() {
        await this.$http.get('roles').then(res => {
          if (res.data.meta.status == 200) {
            this.roleList = res.data.data
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 添加角色
      async addRole() {
        await this.$http.post('roles', this.addForm).then(res => {
          if (res.data.meta.status == 201) {
            this.$message({
              message: res.data.meta.msg,
              type: 'success',
              duration: 600
            })
            this.addDialogVisible = false
            this.getRoleList()
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 显示编辑角色对话框
      async showEditDialog(id) {
        await this.$http.get('roles/' + id).then(res => {
          if (res.data.meta.status == 200) {
            this.editForm = res.data.data
            this.editDialogVisible = true
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      // 编辑角色
      async editRole() {
        await this.$http.put("roles/" + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        }).then(res => {
          if (res.data.meta.status == 200) {
            this.$message({
              message: '更新成功',
              type: 'success',
              duration: 600
            })
            this.editDialogVisible = false
            this.getRoleList()
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      // 关闭编辑对话框
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
        this, this.editDialogVisible = false
      },
      // 删除角色
      async removeRoleById(id) {
        await this.$confirm('确定删除该角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete("roles/" + id).then(res => {
            if (res.data.meta.status == 200) {
              this.getRoleList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              });
            }
          })
        }).catch(err => {
          return err
        });
      },
      // 根据id删除权限
      async removeRightById(role, rightId) {
        await this.$confirm('确定删除该角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete("roles/" + role.id + "/rights/" + rightId).then(res => {
            if (res.data.meta.status == 200) {
              role.children = res.data.data
              this.$message({
                type: 'success',
                message: res.data.meta.msg
              });
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              });
            }
          })
        }).catch(err => {
          return err
        });
      },
      // 显示设置权限对话框
      async showSetRightDialog(role){
        //   保存即将分配权限的角色id
          this.roleId = role.id
          this.defkeys=[]
        // 获取所有权限的数据
        await this.$http.get('rights/tree').then(res => {
            if (res.data.meta.status == 200) {
              this.rightsList = res.data.data
              // 递归获取三级节点的id
              this.getLeafKeys(role,this.defkeys)
              this.setRightDialogVisible=true
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              });
            }
        })
      },
      // 通过递归形式获取角色下所有三级权限的id，并保存到数组中
      getLeafKeys(node,arr){
          // 如果当前node节点不包含children 属性，则是三级节点
          if(!node.children){
              return arr.push(node.id)
          }
          // 如果上一步没有return，证明该node不是三级节点，需要进一步通过调用递归来获取最终的三级节点
          node.children.forEach(item => {
              this.getLeafKeys(item,arr)
          })
      },
      // 监听分配权限对话框的关闭事件
      setRightDialogClosed(){
          this.defkeys = []
      },
      //   分配权限
      async allotRights(){
         //获取树形结构中半选和全选的节点
          const keys = [
              ...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()
          ]
          //拼接成字符串
          const idStr = keys.join(',')
          await this.$http.post('roles/'+this.roleId+'/rights',{rids:idStr}).then(res =>{
            if (res.data.meta.status == 200) {
              this.$message({
                type: 'success',
                message: res.data.meta.msg,
                duration: 600
              });
              this.getRoleList()
              this.setRightDialogVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg,
                duration: 2000
              });
            }
          })
      }
    }
  }

</script>

<style scoped>
  .el-tag {
    margin: 7px
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

</style>
